import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:toolbox/common/sizeConfig.dart';
import 'package:video_player/video_player.dart';

class VideoPlayPage extends StatefulWidget {
  final File file;
  const VideoPlayPage({super.key, required this.file});

  @override
  State<VideoPlayPage> createState() => _VideoPlayPageState();
}

class _VideoPlayPageState extends State<VideoPlayPage> {
  late VideoPlayerController _controller;

  @override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.file(widget.file)..initialize().then((value){
      setState(() {});
    });
    _controller.addListener(() {
      setState(() {});
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void onTap() {
    if (!_controller.value.isInitialized) {
      return;
    }
    if (_controller.value.isCompleted) {
      _controller.seekTo(Duration.zero);
    }
    if (_controller.value.isPlaying) {
      _controller.pause();
    } else {
      _controller.play();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.center,
      children: [
        GestureDetector(
          onTap: onTap,
          child: _controller.value.isInitialized ? AspectRatio(
            aspectRatio: _controller.value.aspectRatio,
            child: VideoPlayer(_controller),
          ) : Container(),
        ),
        IgnorePointer(
          child: Visibility(
            visible: !_controller.value.isPlaying,
            child: const Icon(Icons.play_circle_fill, color: Colors.white, size: 75,),
          ),
        ),
        Positioned(
          top: 40 + SizeConfig.topMargin,
          left: 20,
          child: Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(100),
            ),
            alignment: Alignment.center,
            child: IconButton(
              onPressed: () => Get.back(),
              icon: const Icon(Icons.arrow_back),
            ),
          ),
        ),
      ],
    );
  }
}
